<template>
  <view class="order-container">
    <view class="tabs">
      <view 
        v-for="(item, index) in tabs" 
        :key="index" 
        class="tab-item"
        :class="{ 'active': tabIndex === index }"
        @tap="switchTab(index)"
      >
        {{ item.name }}
      </view>
    </view>

    <view class="orders">
      <view v-if="filteredOrders.length === 0" class="empty">暂无订单</view>
      <view v-for="order in filteredOrders" :key="order.id" class="order-item card">
        <view @click="goToOrderDetails(order.id)">
          <view class="order-header">
            <view class="order-number">订单号：{{ order.ordernumber }}</view>
            <view class="order-status">状态：{{ order.status }}</view>
          </view>
          <view class="order-content">
            <scroll-view class="product-scroll-view" scroll-x>
              <view class="scrollitem" v-for="(product, index) in order.orderProducts" :key="index">
                <image class="scrollimage" :src="product.img" mode="aspectFill"></image>
              </view>
            </scroll-view>
          </view>
          <view class="order-details">
            <view class="order-time">下单时间：{{ formatDateTime(order.create_time) }}</view>
            <view class="order-amount">合计：￥{{ order.total_amount }}</view>
          </view>
        </view>
        <view class="order-actions">
          <view class="actions-container">
            <view v-if="order.status === '待支付'" class="action pay">去支付</view>
            <view v-if="order.status === '未发货'" class="action refund" @tap="handleRefund(order)">退款</view>
			<view v-if="order.status === '已发货'" class="action refund" @tap="handleRefund(order)">退款</view>
            <view v-if="order.status === '已发货'" class="action receive" @tap="handleReceive(order)">确认收货</view>
			<view v-if="order.status === '退款中'" class="action after-sales" @tap="updateCancel(order)">取消退款</view>
            <view v-if="['退款中', '已退款'].includes(order.status)" class="action after-sales" @tap="handleAfterSales(order)">售后详情</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      tabIndex: 0, // 当前激活的标签页索引
      tabs: [
        { id: 1, name: "全部订单" },
        { id: 2, name: "待支付" },
		{ id: 3, name: "待发货" },
        { id: 4, name: "待收货" },
        { id: 5, name: "售后" }
      ],
      orders: [], // 所有订单数据
      filteredOrders: [] // 根据标签页过滤后的订单数据
    };
  },
   onShow() {
	  	this.fetchOrders();
	  },
  methods: {
    switchTab(index) {
      this.tabIndex = index;
      this.filteredOrders = this.filterOrdersByTab(this.tabs[index].name);
    },
    fetchOrders() {
      const token = uni.getStorageSync('Authorization');
      uni.request({
        url: 'http://localhost:8887/Order/selectuser_id',
        method: 'GET',
        header: {
          'Authorization': token,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.orders = res.data.data;
            this.filteredOrders = this.filterOrdersByTab(this.tabs[this.tabIndex].name);
          } else {
            uni.showToast({
              title: '获取订单失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    },
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    handleReceive(order) {
      this.updateOrderStatus(order, '已完成');
    },
    handleRefund(order) {
      this.updateOrderStatus(order, '退款中');
    },
    goToOrderDetails(orderId) {
      uni.navigateTo({
        url: `/pages/orderdetails/orderdetails?id=${orderId}`
      });
    },
    updateOrderStatus(order, newStatus) {
      const token = uni.getStorageSync('Authorization');
      uni.request({
        url: 'http://localhost:8887/Order/updatestatus',
        method: 'POST',
        header: {
          'Authorization': token,
          'Content-Type': 'application/json'
        },
        data: {
          id: order.id,
          status: newStatus
        },
        success: (res) => {
          if (res.data.code === 200 && res.data.data === '修改成功') {
            this.fetchOrders(); 
          } else {
            uni.showToast({
              title: '操作失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    },
	updateCancel(order){
		const token = uni.getStorageSync('Authorization');
		uni.request({
		  url: 'http://localhost:8887/Order/updateCancel',
		  method: 'POST',
		  header: {
		    'Authorization': token,
		    'Content-Type': 'application/json'
		  },
		  data: {
		    id: order.id
		  },
		  success: (res) => {
		    if (res.data.code === 200 && res.data.data === '取消退款成功') {
		      uni.showToast({
		        title: '取消退款成功',
		        icon: 'success'
		      });
		      this.fetchOrders();
		    } else {
		      uni.showToast({
		        title: '操作失败',
		        icon: 'none'
		      });
		    }
		  },
		  fail: () => {
		    uni.showToast({
		      title: '请求失败',
		      icon: 'none'
		    });
		  }
		});
	},
    filterOrdersByTab(tabName) {
      let filtered = this.orders.filter(order => {
        if (tabName === "全部订单") {
          return true;
        } else if (tabName === "待支付") {
          return order.status === "待支付";
        }else if (tabName === "待发货") {
          return order.status === "未发货";
        } else if (tabName === "待收货") {
          return order.status === "已发货";
        } else if (tabName === "售后") {
          return ['退款中', '已退款'].includes(order.status);
        }
      });
      return filtered.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));
    }
  },
  mounted() {
    this.fetchOrders();
  }
};
</script>

<style scoped>
.order-container {
  padding: 15px;
}
.tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  font-size: 16px;
  cursor: pointer;
}
.tab-item.active {
  border-bottom: 2px solid #007aff;
  color: #007aff;
}
.orders {}
.order-item.card {
  background-color: #fff;
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  position: relative;
}
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.order-number{
  font-size: 18px;
  color: #666;
  
}
.order-status {
  font-size: 18px;
  color: #666;
  font-weight: bold;
}
.order-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  color: #666;
  border-top: 1px solid #eee; /* 添加边框 */
}
.order-time {
  font-size: 18px;
} 
.order-amount {
  font-size: 18px;
  font-weight: bold;
}
.order-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.product-scroll-view {
  width: 100%;
  height: 160rpx; /* 增加图片高度 */
  white-space: nowrap;
  overflow-x: auto;
  margin-bottom: 2px;
}
.scrollitem {
  display: inline-block;
  margin-left: 10rpx;
  width: 150rpx; /* 增加图片宽度 */
  height: 150rpx; /* 增加图片高度 */
}
.scrollimage {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}
.order-actions {
  position: absolute;
  bottom: 15px;
  right: 15px;
}
.actions-container {
  display: flex;
  align-items: center;
}
.action {
  padding: 5px 10px;
  margin-left: 10px;
  font-size: 14px;
  border: 1px solid #eee;
  border-radius: 5px;
}
.action:first-child {
  margin-left: 0;
}
.empty {
  text-align: center;
  color: #999;
  margin-top: 50rpx;
}
@media (max-width: 768px) {
  .tab-item {
    font-size: 14px;
  }
  .order-number, .order-status, .order-time, .order-amount {
    font-size: 12px;
  }
  .action {
    padding: 3px 8px;
    font-size: 12px;
  }
}
</style>